package com.p2p.service.vipManagementService.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.p2p.common.DTO.InvestorsDTO;
import com.p2p.common.DTO.InvestorsSelectDTO;
import com.p2p.common.base.RespResult;
import com.p2p.common.base.RespResultCode;
import com.p2p.common.view.InvestorsVo;
import com.p2p.entity.Investors;
import com.p2p.mapper.InvestorsMapper;
import com.p2p.service.vipManagementService.InvestorsService;
import com.p2p.utils.AESUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class InvestorsServiceImpl extends ServiceImpl<InvestorsMapper, Investors> implements InvestorsService {

    @Autowired
    private InvestorsMapper investorsMapper;

    /**
     * 添加投资用户信息
     * @return RespResult
     */
    public RespResult addInvestors(Investors investors){
        log.info("管理员进行添加投资用户操作");

        if (investors!=null&&investors.getIdentityCard()!=null){

            //判断身份证号是否是重复的
            String identityCard1=null;
            try {
                identityCard1 = AESUtils.encrypt(investors.getIdentityCard(), AESUtils.KEY);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            LambdaQueryWrapper<Investors> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(identityCard1),
                    Investors::getIdentityCard,identityCard1);
            List<Investors> investorsList = investorsMapper.selectList(lambdaQueryWrapper);

            //判断是否存在相同的身份证号
            if (investorsList.size()>0){
                return RespResult.error("已经存在该用户了");
            }else {
                //根据当前时间戳生成唯一
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
                String number = sdf.format(System.currentTimeMillis());//202211041552160219

                //补充一个三位随机数
                int x=(int)(Math.random()*900)+100;
                String investorsNum = number + x;
                //设置投资用户编号
                investors.setInvestorsNum(investorsNum);

                //推荐人
                investors.setRecommend("管理员");

                //用户来源
                investors.setUserSource("管理员添加");

                //进行信息加密
                try {
                    String identityCard = AESUtils.encrypt(investors.getIdentityCard(), AESUtils.KEY);
                    investors.setIdentityCard(identityCard);
                    String bankCard = AESUtils.encrypt(investors.getBankCard(), AESUtils.KEY);
                    investors.setBankCard(bankCard);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                investorsMapper.insert(investors);
                log.info("管理员进行添加借款用户：{}操作",investors.getInvestorsName()+"操作成功");
                return RespResult.success();
            }

        }else {
            log.info("添加用户输入实体参数为空");
            return RespResult.error(RespResultCode.ERR_PARAM_NOT_LEGAL.getCode(),RespResultCode.ERR_PARAM_NOT_LEGAL.getMessage(),null);
        }

    }


    /**
     * 更据分页查询投资用户信息
     * @param currentPage 当前页
     * @param pageSize 每页大小
     * @return RespResult
     */
    @Override
    public RespResult findInvestorsList(Integer currentPage, Integer pageSize) {
        log.info("{}进行分页查询投资用户操作",new Date());
        if (currentPage==null&&pageSize==null){
            currentPage=1;
            pageSize=10;
        }

        Page<InvestorsDTO> page=new Page<>(currentPage,pageSize);
        Page<InvestorsDTO> investorsByPage = investorsMapper.findInvestorsByPage(page);
        List<InvestorsDTO> investorsList = investorsByPage.getRecords();

        //将银行卡号和身份证号解密
        for (int i=0;i<investorsList.size();i++){
            //获取数据库中的加密信息
            String identityCard = investorsList.get(i).getIdentityCard();
            String bankCard = investorsList.get(i).getBankCard();
            //进行解密
            try {
                identityCard = AESUtils.decrypt(identityCard, AESUtils.KEY);
                bankCard = AESUtils.decrypt(bankCard, AESUtils.KEY);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //将解密的信息重新赋值
            investorsList.get(i).setIdentityCard(identityCard);
            investorsList.get(i).setBankCard(bankCard);
        }

        Map<String,Object> pageInvestorsMap = new HashMap<>();
        pageInvestorsMap.put("count",investorsByPage.getTotal());
        pageInvestorsMap.put("investorsData",investorsList);

        return RespResult.success(pageInvestorsMap);

    }


    /**
     * 更据id查询投资用户信息
     * @param id 投资用户id
     * @return RespResult
     */
    @Override
    public RespResult findInvestorsById(Long id){
        if (id!=null){
            LambdaQueryWrapper<Investors> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Investors::getIsDeleted,0).
                    eq(Investors::getId,id);
            Investors investors = investorsMapper.selectOne(lambdaQueryWrapper);
            String bankCard = investors.getBankCard();
            String identityCard = investors.getIdentityCard();

            try {
                identityCard = AESUtils.decrypt(identityCard, AESUtils.KEY);
                bankCard = AESUtils.decrypt(bankCard, AESUtils.KEY);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            investors.setBankCard(bankCard);
            investors.setIdentityCard(identityCard);

            return RespResult.success(investors);
        }else {
            return RespResult.error(RespResultCode.ERR_PARAM_NOT_LEGAL.getCode(),RespResultCode.ERR_PARAM_NOT_LEGAL.getMessage(),null);
        }

    }

    /**
     * 修改投资用户信息
     * @param investors 投资用户信息
     * @return RespResult
     */
    @Override
    public RespResult updateInvestors(Investors investors){
        if (investors!=null&&investors.getId()!=null){

            try {
                String identityCard = AESUtils.encrypt(investors.getIdentityCard(), AESUtils.KEY);
                investors.setIdentityCard(identityCard);
                String bankCard = AESUtils.encrypt(investors.getBankCard(), AESUtils.KEY);
                investors.setBankCard(bankCard);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            investorsMapper.updateById(investors);
            return RespResult.success("更新成功");
        }else {
            return RespResult.error(RespResultCode.ERR_PARAM_NOT_LEGAL.getCode(),RespResultCode.ERR_PARAM_NOT_LEGAL.getMessage(),null);
        }
    }

      /**
     * 更据投资用户id修改密码
     * @param id 投资用户id
     * @param loginPwd 登录密码
     * @param payPwd 付款密码
     * @return RespResult
     */
    @Override
    public  RespResult updateInvestorsPwdById(Long id,String loginPwd,String payPwd){
      if (id!=null&&loginPwd!=null&&payPwd!=null){
          investorsMapper.updateInvestorsPwdById(loginPwd,payPwd,id);
          return RespResult.success("更新成功");
      }else {
          return RespResult.error(RespResultCode.ERR_PARAM_NOT_LEGAL.getCode(),RespResultCode.ERR_PARAM_NOT_LEGAL.getMessage(),null);
      }
  }

    /**
     * 更据条件分页查询投资用户信息
     * @param investorsSelectDTO 查询实体
     * @return RespResult
     */
    @Override
    public RespResult findInvestorsByCondition(InvestorsSelectDTO investorsSelectDTO){

        if (investorsSelectDTO!=null){

            if (investorsSelectDTO.getCurrentPage()==null||investorsSelectDTO.getCurrentPage()==null){
                investorsSelectDTO.setCurrentPage(1);
                investorsSelectDTO.setPageSize(10);
                }
            Page<InvestorsDTO> page=new Page<>(investorsSelectDTO.getCurrentPage()
                    ,investorsSelectDTO.getPageSize());
            Page<InvestorsDTO> investorsByPage = investorsMapper.findInvestorsByCondition(page,
                    investorsSelectDTO.getInvestorsName(),
                    investorsSelectDTO.getPhoneNum(),
                    investorsSelectDTO.getAuthenticationStatus(),
                    investorsSelectDTO.getLockStatus(),
                    investorsSelectDTO.getUserSource());

            List<InvestorsDTO> investorsList = investorsByPage.getRecords();
            //将银行卡号和身份证号解密
            for (int i=0;i<investorsList.size();i++){
                //获取数据库中的加密信息
                String identityCard = investorsList.get(i).getIdentityCard();
                String bankCard = investorsList.get(i).getBankCard();
                //进行解密
                try {
                    identityCard = AESUtils.decrypt(identityCard, AESUtils.KEY);
                    bankCard = AESUtils.decrypt(bankCard, AESUtils.KEY);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                //将解密的信息重新赋值
                investorsList.get(i).setIdentityCard(identityCard);
                investorsList.get(i).setBankCard(bankCard);
            }

            Map<String,Object> pageInvestorsMap = new HashMap<>();
            pageInvestorsMap.put("count",investorsByPage.getTotal());
            pageInvestorsMap.put("investorsData",investorsList);

            return RespResult.success(pageInvestorsMap);
        }else {
            return RespResult.error(RespResultCode.ERR_PARAM_NOT_LEGAL.getCode(),RespResultCode.ERR_PARAM_NOT_LEGAL.getMessage(),null);
        }
    }


    /**
     * 根据id删除投资用户信息
     * @param id 投资id
     * @return RespResult
     */
    @Transactional
    @Override
    public RespResult delInvestorsById(Long id) {
        if (id!=null){
            investorsMapper.deleteById(id);
            investorsMapper.deleteLoginDate(id);
            return RespResult.success("删除成功");
        }else {
            return RespResult.error(RespResultCode.ERR_PARAM_NOT_LEGAL.getCode(),RespResultCode.ERR_PARAM_NOT_LEGAL.getMessage(),null);
        }

    }
}
